Mootools IntervalController mixin
You can also be interested in:
How many times do you need to implement a functionality which has to be run every n seconds and possibly should be stopped and resumed? Not so often probably but it happens and happened to me just today, for this reason I decided to write a mootools Mixin so that I can reuse this code when I need it.
The code
/**
* IntervalController Mixin
* Provides methods to start, stop and resume
* a setInterval functionality
*/
var IntervalController = new Class({
_started: false,
_handler: null,
_callback: null,
_interval: null,
startInterval: function(callback, interval) {
this._callback = callback;
this._interval = interval;
this._handler = setInterval(callback, interval);
this._started = true;
},
stopInterval: function() {
if(this._handler === null) {
console.log("nothing to stop");
}
else {
clearInterval(this._handler);
this._handler = null;
}
},
resumeInterval: function() {
if(!this._started) {
console.log("not yet started");
}
else if(this._handler !== null) {
console.log("already running");
}
else {
this._handler = setInterval(this._callback, this._interval);
}
}
});
The mixin provides three public methods.
(void) startInterval(callback, interval)
callback: the function to be called every interval ms.
interval: the loop interval.
Starts the loop invoking the js setInterval then stores its handler and the passed parameters.
(void) stopInterval()
Stops the loop.
(void) resumeInterval()
Resumes the loop using the previously stored parameters.
How to use it
Now it's time to use our new mixin, fortunately it's quite simple, just pass it to the implement mutator (as the Options extra class) and all its methods become available in your class.
var MyClass= new Class({
Implements: [IntervalController],
initialize: function() {
// here you may use the startInterval, stopInterval and resumeInterval methods
}
})
You may see the mixin in action in a "Bounce Showcase" widget I've posted on codepen.
Your Smartwatch Loves Tasker!
Your Smartwatch Loves Tasker!
Featured
Archive
- 2021
- 2020
- 2019
- 2018
- 2017
- Nov
- Oct
- Aug
- Jun
- Mar
- Feb
- 2016
- Oct
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2015
- Nov
- Oct
- Aug
- Apr
- Mar
- Feb
- Jan
- 2014
- Sep
- Jul
- May
- Apr
- Mar
- Feb
- Jan
- 2013
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2012
- Dec
- Nov
- Oct
- Aug
- Jul
- Jun
- May
- Apr
- Jan
- 2011
- Dec
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May